package io.renren.modules.yunxin;

import com.alibaba.fastjson.JSONObject;

import io.renren.common.utils.SpringContextUtil;
import io.renren.common.utils.StringUtils;
import io.renren.config.YunxinConfig;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.*;

public class YunxinUtils {


    public static String appKey = null;
    public static String appSecret = null;

    private static Logger log = LoggerFactory.getLogger(YunxinUtils.class);

    public static void main1(String[] args) throws Exception {
        register("65b68d0b89d64dd7b7f69ceaf296addd");
    }

    private static void initKey() {
        if (appSecret == null || appKey == null) {
            YunxinConfig config = SpringContextUtil.getBean(YunxinConfig.class);
            appKey = config.getKey();
            appSecret = config.getSecret();
        }
    }


    public static String postYunxin(String url, Map<String, Object> param) throws Exception {
        initKey();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);


        String nonce = StringUtils.getUUID();
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(appSecret, nonce, curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");


        Iterator<Map.Entry<String, Object>> iterator = param.entrySet().iterator();

        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<>();

        while (iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            if (next.getValue() != null || next.getKey().equals("url")) {
                nvps.add(new BasicNameValuePair(next.getKey(), String.valueOf(next.getValue())));
            }
        }
        if (nvps.size() > 0) {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        }

        CloseableHttpResponse response = httpClient.execute(httpPost);

        String ret = EntityUtils.toString(response.getEntity(), "utf-8");

        JSONObject jsonRet = JSONObject.parseObject(ret);
        if (jsonRet.isEmpty() || jsonRet.getInteger("code") != 200) {
            log.error("云信操作失败 :" + ret);
            throw new Exception("云信操作失败");
        }
        return ret;
    }

    public static boolean register(String yunxinAccount) throws Exception {
        initKey();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "https://api.netease.im/nimserver/user/create.action";
        HttpPost httpPost = new HttpPost(url);


        String nonce = StringUtils.getUUID();
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(appSecret, nonce, curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("accid", yunxinAccount));
        nvps.add(new BasicNameValuePair("token", "123456"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        // 执行请
        CloseableHttpResponse response = httpClient.execute(httpPost);

        String ret = EntityUtils.toString(response.getEntity(), "utf-8");

        JSONObject jsonRet = new JSONObject();
        log.info("注册返回 :" + ret);
        try {
            jsonRet = JSONObject.parseObject(ret);
            if (jsonRet.isEmpty() || jsonRet.getInteger("code") != 200) {
                throw new Exception("注册IM账号失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("注册云信异常: " + ret);
            throw new Exception("注册IM账号失败");
        }


        return true;
    }


    // 计算并获取CheckSum
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    // 计算并获取md5值
    public static String getMD5(String requestBody) {
        return encode("md5", requestBody);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest
                    = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

}
